package com.maxd.controller.apple;

import com.alibaba.fastjson.JSONObject;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.Orders;
import com.maxd.model.PayDetails;
import com.maxd.model.UserMoneyDetails;
import com.maxd.respository.pay.PayDetailsJpaRepository;
import com.maxd.respository.pay.PayDetailsRepository;
import com.maxd.respository.selfOrder.OrdersJpaRepository;
import com.maxd.service.pay.PayDetailsService;
import com.maxd.service.selfOrder.OrdersService;
import com.maxd.service.userMoney.UserMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyService;
import com.maxd.utils.AmountCalUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fang
 * @date 2020/11/4
 */
@Slf4j
@RestController
@Api(value = "苹果支付", tags = {"苹果支付"})
@RequestMapping(value = "/apple")
public class ApplePayController {

    @Autowired
    private PayDetailsJpaRepository payDetailsJpaRepository;
    @Autowired
    private PayDetailsRepository payDetailsRepository;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private OrdersService ordersService;

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @ApiOperation("支付")
    @PostMapping("/pay")
    public Result pay(Long userId, String money)  {
        String generalOrder = getGeneralOrder();
        PayDetails payDetails=new PayDetails();
        payDetails.setState(0);
        payDetails.setCreateTime(sdf.format(new Date()));
        payDetails.setOrderId(generalOrder);
        payDetails.setUserId(userId);
        payDetails.setMoney(AmountCalUtils.divide(Double.parseDouble(money),100));
        payDetails.setClassify(1);
        payDetailsJpaRepository.save(payDetails);
        Map<String,Object> map=new HashMap<>();
        map.put("orderNo",generalOrder);
        map.put("money",money);
        return ResultUtil.success(map);
    }

    @ApiOperation("商品支付")
    @PostMapping("/shopPay")
    public Result shopPay(String orderNo)  {
        Orders orders = ordersService.findByOrderNum(orderNo);
        if(orders!=null && orders.getStatus()==1){
            Map<String,Object> map=new HashMap<>();
            map.put("orderNo",orderNo);
            map.put("money",orders.getPayMoney());
            return ResultUtil.success(map);
        }
        return  ResultUtil.error(9999,"订单状态异常，请刷新后重试！");
    }




    @RequestMapping(value="/pay/order/notifyCallBack")
    @ResponseBody
    public Result applepayOrderNotifyCallBack(String transactionId, String payload) {
        log.info("苹果支付客户端传过来的值 transactionId: " + transactionId + ",客户端传过来的值 payload: " + payload);
        try {
            String verifyResult = IosVerifyUtil.buyAppVerify(payload, 1); 			//1.先线上测试    发送平台验证
            if (verifyResult == null) {   											// 苹果服务器没有返回验证结果
                log.info("无订单信息!");
                ResultUtil.error(9999,"无订单信息");
            } else {  	    														// 苹果验证有返回结果
                log.info("线上，苹果平台返回JSON:" + verifyResult);
                JSONObject job = JSONObject.parseObject(verifyResult);
                String states = job.getString("status");

                //0 正常
                //21000 App Store不能读取你提供的JSON对象
                //21002 receipt-data域的数据有问题
                //21003 receipt无法通过验证
                //21004 提供的shared secret不匹配你账号中的shared secret
                //21005 receipt服务器当前不可用
                //21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
                //21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
                //21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
                if("21007".equals(states)){											//是沙盒环境，应沙盒测试，否则执行下面
                    verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);			//2.再沙盒测试  发送平台验证
                    log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
                    job = JSONObject.parseObject(verifyResult);
                    states = job.getString("status");
                }

                log.info("苹果平台返回值：job" + job);
                if ("0".equals(states)){ // 前端所提供的收据是有效的    验证成功
                    String receipt = job.getString("receipt");
                    JSONObject returnJson = JSONObject.parseObject(receipt);
                    String inApp = returnJson.getString("in_app");
                    JSONObject inAppJson = JSONObject.parseObject(inApp.substring(1, inApp.length() - 1));

                    String productId = inAppJson.getString("product_id");
                    String transactionIds = inAppJson.getString("transaction_id");   // 订单号

                    //如果单号一致  则开始处理逻辑
                    if(transactionId.equals(transactionIds)){
//                        String[] moneys = productId.split("\\.");//实际支付金额
                        PayDetails payDetails = payDetailsRepository.selectByOrderId(transactionId);
                        if(payDetails!=null && payDetails.getState()==0){
                            payDetailsRepository.updateState(payDetails.getId(),1,new Date());
                            userMoneyService.updateMoney(1,payDetails.getUserId(),payDetails.getMoney());
                            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                            userMoneyDetails.setUserId(payDetails.getUserId());
                            userMoneyDetails.setTitle("充值："+payDetails.getMoney());
                            userMoneyDetails.setContent("苹果支付充值金额："+payDetails.getMoney());
                            userMoneyDetails.setType(1);
                            userMoneyDetails.setMoney(payDetails.getMoney());
                            userMoneyDetails.setCreateTime(sdf.format(new Date()));
                            userMoneyDetailsService.save(userMoneyDetails);
                        }else{
                            Orders orders = ordersService.findByOrderNum(transactionId);
                            if(orders!=null && orders.getStatus()==1){
                                orders.setPayWay(2); //支付方式为2支付宝
                                orders.setStatus(2); //已付款
                                orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                                ordersService.updateBody(orders);
                                //订单分销
                                ordersService.fenXiao(orders.getId());
                            }
                        }
                    }
                   return ResultUtil.success();
                } else {
                    return ResultUtil.error(9999,"订单无效!");
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResultUtil.error(9999,"订单存在异常，请刷新后重试！");
    }


    public String getGeneralOrder(){
        Date date=new Date();
        String newString = String.format("%0"+4+"d", (int)((Math.random()*9+1)*1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format+newString;
    }


}